package com.bw.permission.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bw.permission.config.AjaxResult;
import com.bw.permission.entity.User;
import com.bw.permission.entity.UserRole;
import com.bw.permission.entity.UserVo;
import com.bw.permission.service.IUserRoleService;
import com.bw.permission.service.IUserService;
import com.bw.permission.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2020-10-28
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("login")
    public AjaxResult login(@RequestBody User user){
        //认证：判断用户名和密码是否正确
        //验证用户名或密码是否为空
        if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())){
            return AjaxResult.err(10000,"用户名或密码不能为空");
        }
        //验证用户是否存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",user.getUsername());
        User userInfo = iUserService.getOne(queryWrapper);
        if(userInfo==null){
            return AjaxResult.err(10000,"用户不存在");
        }
        //验证用户是否被禁用
        if(!userInfo.getEnabled()){
            return AjaxResult.err(10000,"用户被禁用，请联系管理员");
        }
        //验证密码是否正确
        if(!user.getPassword().equals(userInfo.getPassword())){
            return AjaxResult.err(10000,"用户名或密码错误");
        }
        //授权：根据用户Id，查询他具有哪些权限：权限编码:user:list:query;user:add;user:del;

        //如果验证通过，给前端返回用户登录名称或用户Id
        userInfo.setPassword(null);
        userInfo.setToken(jwtUtils.createToken(JSON.toJSONString(user)));
        return AjaxResult.ok(userInfo);
    }


    @GetMapping("list")
    public AjaxResult list(UserVo userVo, Page page){

//        List<HashMap<String, Object>> sexList = SexEnum.getSexList();

        IPage<UserVo> pageInfo = iUserService.getPageInfo(userVo,page);
        return AjaxResult.ok(pageInfo);
    }

    /**
     * 保存（新增或修改）
     * @param user
     * @return
     */
    @PostMapping("save")
    public AjaxResult save(@RequestBody  UserVo user){
        //创建用户时，设置默认密码
        if(user.getId()==null){
            user.setPassword("123456");
        }
        //保存用户信息
        boolean b = iUserService.saveOrUpdate(user);
        return AjaxResult.ok(b);
    }

    @PostMapping("authRoles")
    @Transactional
    public AjaxResult authRoles(@RequestBody User user){
        //删除中间表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("uid",user.getId());
        iUserRoleService.remove(queryWrapper);
        //插入用户角色表
        List<UserRole> userRoles = new ArrayList<>();
        if(user.getRoleIds()!=null){
            user.getRoleIds().forEach(roleId->{
                UserRole userRole = new UserRole();
                userRole.setUid(user.getId());
                userRole.setRid(roleId);
                userRoles.add(userRole);
            });
        }
        iUserRoleService.saveBatch(userRoles);
        return AjaxResult.ok(null);
    }

    @GetMapping("getLoginUserInfo")
    public AjaxResult getLoginUserInfo(HttpServletRequest request){
        String username = jwtUtils.getCurUsername();
        User byUsername = iUserService.getByUsername(username);
        return AjaxResult.ok(byUsername);
    }

    @PostMapping("batchDel")
    public AjaxResult batchDel(@RequestBody UserVo userVo) {
        if (userVo.getIdList() != null && userVo.getIdList().size() > 0) {
            iUserService.removeByIds(userVo.getIdList());
        }
        return AjaxResult.ok();
    }

}
